package com.beagle.njddapp.net;

import android.content.Intent;
import android.net.ParseException;
import android.util.Log;

import com.alibaba.fastjson.JSONObject;

import com.beagle.njddapp.base.BaseApplication;
import com.beagle.njddapp.core.UserApi;
import com.beagle.njddapp.core.UserService;
import com.beagle.njddapp.ui.activity.LoginActivity;
import com.beagle.njddapp.utils.PrefsManager;
import com.blankj.utilcode.util.ActivityUtils;
import com.blankj.utilcode.util.LogUtils;
import com.google.gson.JsonParseException;


import org.json.JSONException;

import java.net.ConnectException;
import java.net.SocketTimeoutException;

import io.reactivex.Observer;
import io.reactivex.disposables.Disposable;
import retrofit2.HttpException;

import static com.beagle.njddapp.core.UserService.TOKEN;


/**
 * Created by cyb on 2018/11/5.
 * 这是用来解析返回数据的,基于io.reactivex.Observer
 */

 public abstract class HttpResponseObserver<T> implements Observer<T> {

    private static final int UNAUTHORIZED = 401;
    private static final int FORBIDDEN = 403;
    private static final int NOT_FOUND = 404;
    private static final int REQUEST_TIMEOUT = 408;
    private static final int INTERNAL_SERVER_ERROR = 500;
    private static final int BAD_GATEWAY = 502;
    private static final int SERVICE_UNAVAILABLE = 503;
    private static final int GATEWAY_TIMEOUT = 504;


    @Override
    public void onError(Throwable e) {
        LogUtils.e( Log.getStackTraceString(e));
        LogUtils.d(e.toString());
        String errorStr = "";
        //数据解析异常
//       if (e instanceof Exception) {
//           errorStr = e.getMessage();
//       }
//
        if (e instanceof HttpException) {
            HttpException httpException = (HttpException) e;
            switch (httpException.code()) {
                case UNAUTHORIZED:
                case FORBIDDEN:
                case NOT_FOUND:
                case REQUEST_TIMEOUT:
                case GATEWAY_TIMEOUT:
                case INTERNAL_SERVER_ERROR:
                case BAD_GATEWAY:
                case SERVICE_UNAVAILABLE:
                default:
                    errorStr = "网络错误,请检查网络并重试";
                    break;
            }
            error(-1,errorStr);
        } else if (e instanceof RuntimeException) {
            errorStr = "服务器异常，请稍后重试";
        } else if (e instanceof JsonParseException
                || e instanceof JSONException
                || e instanceof ParseException) {

            errorStr = "解析错误，请重试";
        } else if (e instanceof ConnectException) {
            errorStr = "连接失败，请检查网络并重试";
        }else if(e instanceof SocketTimeoutException){
            errorStr = "连接超时，请检查网络并重试";
        } else if (e instanceof javax.net.ssl.SSLHandshakeException) {
            errorStr = "证书验证失败，请重试";
        }else if(e instanceof HttpException){
            errorStr = "服务器异常，请重试";
        } else {
            errorStr = "请求失败，请检查网络并重试";
        }

        error(-1,errorStr);
    }

    @Override
    public void onNext(T data) {
        if (data==null){
            error(-1 ,"请重试");
            return;
        }
//        LogUtils.d("onNext");

        try {

            if (data instanceof BaseResponse) {
                //基础数据
                BaseResponse baseResponse = (BaseResponse) data;
                //对于所有的网络请求，1-成功 : -0,失败
                int code = baseResponse.getResponseCode();
                LogUtils.d("onNext1 :"+code);

                String message = baseResponse.getResponseMsg()==null?"":baseResponse.getResponseMsg();
                if (code == 0) {
                    success(data);
                } else if (code==100005||code==1001){
                    UserService.getInstance().setUserInfoBean(null);
                    UserService.getInstance().setRole(-1);
                    UserService.getInstance().setToken("");
                    UserService.getInstance().setPhone("");
                    PrefsManager.getInstance(BaseApplication.getInstance()).putString(TOKEN,"");
                    PrefsManager.getInstance(BaseApplication.getInstance()).clear();
                    ActivityUtils.finishAllActivities();
                    ActivityUtils.startActivity(LoginActivity.class);
                }else {
                    error(code, message);
                }

            }else if (data instanceof BaseStringResponseBean){
                BaseStringResponseBean stringResponseBean= (BaseStringResponseBean) data;
                int code= Integer.parseInt(stringResponseBean.getCode());
                LogUtils.d("onNext2 :"+code);
                if (code == 0) {
                    success(data);
                } else if (code==100005){
                    ActivityUtils.finishAllActivities();
                    ActivityUtils.startActivity(LoginActivity.class);
                    error(code,"登录过期");
                }else {
                    error(code, stringResponseBean.getDesc());
                }

            }else {
                JSONObject jsonObject = (JSONObject) data;
                int code = jsonObject.getIntValue("code");
                LogUtils.d("onNext3 :"+code);
                String msg = jsonObject.getString("msg")==null?"":jsonObject.getString("msg");
                if (code==0){
                    success(data);
                }else {
                    error(code, msg);
                }
            }
        }catch (Exception e){
            LogUtils.d("onNext4 :"+e.toString());
        }
    }

    public abstract void success(T t);
    public abstract void error(int code, String message);
    @Override
    public void onComplete() {
    }

    @Override
    public void onSubscribe(Disposable d) {
    }


}
